import React, { useEffect, useState, useRef } from 'react';
import styles from './index.less';

const Observer: React.FC = () => {

    const [count, setCount] = useState(0);
    const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
    const divRef = useRef(null);
    const ccRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const observer = new ResizeObserver((entries, observer) => {
            for (let entry of entries) {

                if (entry.target === divRef.current) {
                    observer.unobserve(entry.target);
                }
            }
        });

        if (divRef.current) {
            observer.observe(divRef.current);
        }

        console.log('choayue-111', ccRef.current?.getBoundingClientRect());

        return () => {
            if (divRef.current) {
                observer.unobserve(divRef.current);
            }

            observer.disconnect();
        };
        
    }, []);

    return (
        <>
            <div>
                <div
                    ref={divRef}
                    style={{ width: '350px', height: '100px', border: '1px solid black' }}
                >
                    这个 div 的大小可以被监听
                </div>
                <p>宽度: {dimensions.width}px</p>
                <p>高度: {dimensions.height}px</p>
            </div>
            <div ref={ccRef} className={styles.scroll}>
                
            </div>
        </>
    );
};

export default Observer;
